import { Component, OnInit, ViewChild } from '@angular/core';
import { statusLists, typeLists, findProjectModel, addProjectModel } from './project-type.model';
import { Router } from '@angular/router';
import { ProjectService } from '../../services/project/project.service';
import { ZzjFileUploader, FlowFileModel } from '@zzj/nag-file-uploader';
import { FILEURL } from './../../config';
import { NzModalService, NzMessageService } from 'ng-zorro-antd';
import { Utils } from 'src/app/common/helper/util-helper';
import { listModel } from '../project/model-list/model-list.model';
import { projectInfo } from '../project/survey/survey.model';
declare const BMap: any;
@Component({
  selector: 'app-project-type',
  templateUrl: './project-type.component.html',
  styleUrls: ['./project-type.component.scss']
})
export class ProjectTypeComponent implements OnInit {


  public constructor(
    private router: Router,
    private protectedService: ProjectService,
    private modalService: NzModalService,
    private message: NzMessageService
  ) {
  }

  @ViewChild('imageUploader', { static: false }) imageUploader: ZzjFileUploader;
  @ViewChild('imageEditUploader', { static: false }) imageEditUploader: ZzjFileUploader;
  @ViewChild('AddressInput', { static: false }) input;
  // public addJson = {
  //   Location: null
  // };
  public _click: any;
  public showJson: any = {};
  public mapKeyWordList = [];
  public mapAddress = '';
  public mapLocation = '';
  public _map: any;
  public projectLists: any = [];
  public iconStyle: any = {};
  public nzTotal = 0;
  public nzPageIndex = 1;
  public isAddVisible = false;
  // public addimgShow: boolean = true;
  // public addimgStyle: any = {};
  private FILEURL = FILEURL;
  public imageQueue: any = [];
  public findProject = new findProjectModel();
  public addProjectModel = new addProjectModel();
  // public isEditVisible: boolean = false;
  // public editimgShow: boolean = true;
  // public editimgStyle: any = {};
  // public editProjectModel: any = {};
  public typeLists = typeLists;
  public statusLists = statusLists;
  public isShowChoosePoint = false;

  public status = {
    primaryId: JSON.parse(window.localStorage.getItem('APDInfo'))['primaryId'],
    // 当前用户的ID
    userId: JSON.parse(window.localStorage.getItem('APDInfo'))['userId'],
    // // 当前页面所需要的权限
    pagePermissions: [
      'APJ.Project.Manage'
    ],
    // // 当前页面权限
    pageAuthorty: {
      ProjectManage: null
    },

  };



  // 百度地图
  options: any;

  /**
   * 初始化
   */
  public async init() {
    // 初始化企业级权限匹配
    this.status.pageAuthorty = Utils.grantedPermissions(
      this.status.pagePermissions,
      this.status.pageAuthorty,
      true
    );
    console.log(this.status.pageAuthorty);
    const result = await this.protectedService.getProjects(this.findProject);
    this.nzTotal = result.result.totalCount;
    this.projectLists = result.result.items;
    this.getImg(this.projectLists);
  }

  public async pageChange(index) {
    this.findProject.skipCount = index - 1;
    await this.init();
  }

  public getImg(data) {
    data.forEach(el => {
      if (el.imageUrl) {
        el.img = { 'background-image': 'url(' + el.imageUrl + ')' };
      }
    });
  }

  public async search() {
    this.findProject.skipCount = 0;
    await this.init();
  }

  public async fileChange(e) {
    this.imageUploader.add(e.target.files[0]);
  }

  public fileSuccess(transfer: FlowFileModel) {
    // this.addimgShow = false;
    // this.addimgStyle = {
    //   'background-image': 'url(' + transfer.url + ')'
    // }
    this.addProjectModel.imageUrl = transfer.url;
  }

  public async handleOk() {
    if (this.addProjectModel.name === undefined || this.addProjectModel.name === '') {
      this.message.create('warning', `项目名字不能为空`);
      return;
    }
    if (this.addProjectModel.code === undefined || this.addProjectModel.code === '') {
      this.message.create('warning', `项目编号不能为空`);
      return;
    }
    // 手机号
    if (this.addProjectModel.companyLinkphone && this.addProjectModel.companyLinkphone !== '') {
      if (this.addProjectModel.companyLinkphone.length !== 11 || isNaN(parseInt(this.addProjectModel.companyLinkphone))) {
        this.message.create('warning', '请输入正确的联系电话');
        return;
      }
    }
    // 新建项目时，项目创建人拥有项目所有权限
    // this.addProjectModel.PIpermission =
    // tslint:disable-next-line: max-line-length
    this.addProjectModel.permissionArray = ['APJ.PI.CheckItems', 'APJ.PI.CreateSelf', 'APJ.PI.Delete', 'APJ.PI.Drawings', 'APJ.PI.Edit', 'APJ.PI.Logs', 'APJ.PI.Models', 'APJ.PI.Move', 'APJ.PI.NewFolder', 'APJ.PI.ProjectUser', 'APJ.PI.Up', 'APJ.PI.View', 'APJ.PI.ViewSelf'];
    const ret = await this.protectedService.addProjects(this.addProjectModel);
    if (ret) {
      this.isAddVisible = false;
      this.message.create('success', '操作成功');
      this.init();
    }

  }

  /**
   * 修改
   * @param item
   */
  public editProject(item) {

    this.addProjectModel = new addProjectModel(item);

    this.addProjectModel.isImportant = this.addProjectModel.isImportant + '';
    this.addProjectModel.isApprove = this.addProjectModel.isApprove + '';
    this.addProjectModel.mark = this.addProjectModel.mark + '';

    this.isAddVisible = true;
    // this.editProjectModel = new addProjectModel(item);
    // console.log(this.editProjectModel)

    // this.isEditVisible = true;
    // this.editimgShow = true;
    // this.editimgStyle = {};
  }



  // 项目地址选择
  choosePoint() {
    this.isShowChoosePoint = true;
  }


  // 搜索地址 键盘事件
  async keyEvent() {
    const address = this.addProjectModel.address;
    const map = this._map;
    // const myKeys = [address];
    console.log(this.addProjectModel.address);
    const res = await this.mapSearch(map, address);
    this.mapKeyWordList = res;
    if (res[0]) {
      this.addProjectModel.location = res[0].point.lng + ',' + res[0].point.lat;
    }
    // console.log(this.mapKeyWordList)
  }

  // 封装百度搜索接口
  mapSearch(map, add): Promise<any> {
    return new Promise((resolve) => {
      const local = new BMap.LocalSearch(map,
        {
          onSearchComplete: (result) => {
            if (result) {
              resolve(result.Ar);
            }
          }
        }
      );
      local.search(add);
    });
  }


  blurEvent() {
    setTimeout(() => {
      this.mapKeyWordList = [];
    }, 100);
  }
  // 选择搜索结果
  public chooseAddress(idx) {
    const currentAddress = this.mapKeyWordList[idx];
    // console.log(currentAddress)
    const title = currentAddress.address;
    const point = currentAddress.point;
    this.addProjectModel.address = title;
    this.mapKeyWordList = [];
    // 点样式
    const myIcon = new BMap.Icon('http://api.map.baidu.com/img/markers.png', new BMap.Size(23, 25), {
      offset: new BMap.Size(10, 25),                  // 指定定位位置
      imageOffset: new BMap.Size(0, -275)   // 设置图片偏移
    });
    // console.log(this.showJson.Address)
    if (point) {
      const map = this._map;
      const allOverlay = map.getOverlays();
      map.clearOverlays();
      const mapPoint = new BMap.Point(point.lng, point.lat);
      map.centerAndZoom(mapPoint, 11);
      const marker = new BMap.Marker(mapPoint, { icon: myIcon });  // 创建标注
      map.addOverlay(marker);               // 将标注添加到地图中
      marker.enableDragging();
      const geoc = new BMap.Geocoder();
      const that = this;
      marker.addEventListener('mouseup', (e) => {
        // let p = marker.getPosition();
        const pt = e.point;
        geoc.getLocation(pt, function (rs) {
          console.log(rs);
          const addComp = rs.addressComponents;
          // console.info(rs)
          const address = rs.address + (rs.business ? '[' + rs.business + ']' : '');
          const location = pt.lng + ',' + pt.lat;
          // console.info(location)
          that.addProjectModel.address = address;
          that.addProjectModel.location = location;
          // this.setAddress(address, location);
          // this.mapAddress = address;
          // alert(addComp.province + ", " + addComp.city + ", " + addComp.district + ", " + addComp.street + ", " + addComp.streetNumber);
        });
      });

      // 保存经纬度
      this.addProjectModel.location = point.lng + ',' + point.lat;
    }

  }
  // 确定选点结束
  protected handleOkpoint() {

    if (!this.addProjectModel.address) {
      this.message.warning('项目地址不能为空');
      return;
    }
    if (!this.addProjectModel.location) {
      this.message.warning('请点击地图进行标记');
      return;
    }
    if (this.addProjectModel.location && this.addProjectModel.address) {
      this.isShowChoosePoint = false;
    }
  }
  public onReady(map: any) {
    // console.log(11);
    this._map = map;
    // 点样式
    const myIcon = new BMap.Icon('http://api.map.baidu.com/img/markers.png', new BMap.Size(23, 25), {
      offset: new BMap.Size(10, 25),                  // 指定定位位置
      imageOffset: new BMap.Size(0, -275)   // 设置图片偏移
    });
    map.centerAndZoom(new BMap.Point(106.561317, 29.561393), 11);
    // map.setCurrentCity('重庆');
    map.enableScrollWheelZoom(true);
    const that = this;
    const showJson = this.showJson;
    const geoc = new BMap.Geocoder();
    map.addEventListener('click', (e) => {
      const point = e.point;
      geoc.getLocation(point, function (rs) {
        const address = rs.address + (rs.business ? '[' + rs.business + ']' : '');
        const location = point.lng + ',' + point.lat;

        setTimeout(() => {
          that.addProjectModel.address = address;
          that.addProjectModel.location = location;

        }, 10);
        window.localStorage.setItem('myMapLocation', location);
        that.input.nativeElement.value = address;

        map.clearOverlays();
        const mapPoint = new BMap.Point(point.lng, point.lat);
        const marker = new BMap.Marker(mapPoint, { icon: myIcon });  // 创建标注
        map.addOverlay(marker);               // 将标注添加到地图中
        marker.enableDragging();
        marker.addEventListener('mouseup', (e) => {
          const pt = e.point;
          geoc.getLocation(pt, function (rs) {
            const address = rs.address + (rs.business ? '[' + rs.business + ']' : '');
            const location = pt.lng + ',' + pt.lat;
            // console.info(location);
            that.addProjectModel.address = address;
            that.addProjectModel.location = location;
            that.input.nativeElement.value = address;
          });
        });
      });
    });
    this.removeBaiduLogo();
  }


  private removeBaiduLogo() {
    try {
      const tagQuery: any = document.querySelector('.anchorBL');
      tagQuery.style.display = 'none';
      const spanQuery: any = document.querySelector('.BMap_cpyCtrl.BMap_noprint.anchorBL');
      console.log(spanQuery);
      spanQuery.style.display = 'none';
    } catch (error) { }
  }



  /**
   * 删除
   * @param id
   */
  public deleteProject(id) {
    this.modalService.error({
      nzTitle: '确认要删除这个项目吗?',
      nzContent: '<b style="color: red;">删除后不能恢复，请谨慎操作。</b>',
      nzOkText: '确定',
      nzOkType: 'danger',
      nzOnOk: async () => {
        await this.protectedService.deleteProjects({ input: id });
        this.init();
      },
      nzCancelText: '取消',
      nzOnCancel: () => { }
    });
  }

  /**
   * 搜索
   */
  public async screen() {
    this.findProject.skipCount = 0;
    console.log(this.findProject);
    await this.init();
  }

  /**
   * 搜索框回车事件
   * @param e <Event>
   */
  public keyupEvent(e: Event) {
    Utils.enter(e, this.screen.bind(this));
  }

  /**
   * 重置
   */
  public async reset() {
    this.findProject = new findProjectModel();
  }

  /**
   * 路由
   * @param item
   */
  public async routerTo(item) {
    // console.log(item)
    const params = {
      code: item.code,
    };
    // 根据项目code查询智慧工地项目id
    const res = await this.protectedService.QueryProjectPagedList(params);


    if (res.result.items.length !== 0) {
      item.smartSiteId = res.result.items[0].id;
      const projectId = item.id;
      window.localStorage.setItem('project', JSON.stringify(item));
      this.router.navigate(
        [`/inner/project/${projectId}/survey`],
        { queryParams: { info: 'project', id: 'init' } }
      );
    } else  {
      this.message.warning('智慧工地相关信息获取失败');
      const projectId = item.id;
      window.localStorage.setItem('project', JSON.stringify(item));
      this.router.navigate(
        [`/inner/project/${projectId}/survey`],
        { queryParams: { info: 'project', id: 'init' } }
      );
    }
  }

  public handleCancel() {
    this.isAddVisible = false;
    console.log(this.addProjectModel);
    // tslint:disable-next-line: forin
    for (const key in this.addProjectModel) {
      this.addProjectModel[key] = null;
    }


    // this.isEditVisible = false;
  }
  public chooseCancel() {
    this.isShowChoosePoint = false;
  }

  public ngOnInit() {
    this.init();
  }

}
